<template>
  <div class="login-page">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="bg-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
        <div class="shape shape-4"></div>
      </div>
    </div>

    <!-- 顶部Logo区域 -->
    <div class="login-header">
      <div class="logo-section">
        <div class="logo">
          <img src="/logo-top.8ad5fc81.png" alt="CMP Logo" class="logo-img" />
        </div>
      </div>
    </div>

    <!-- 登录表单容器 -->
    <div class="login-container">
      <!-- 登录方式切换 -->
      <van-tabs v-model:active="activeTab" @change="onTabChange" class="login-tabs">
        <van-tab title="用户登录" name="username"></van-tab>
        <van-tab title="手机号登录" name="phone"></van-tab>
      </van-tabs>

      <!-- 用户名登录表单 -->
      <van-form @submit="onSubmit" class="login-form" v-if="activeTab === 'username'">
        <div class="form-group">
          <van-field
            v-model="loginForm.username"
            name="username"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
            left-icon="user-o"
            class="custom-field"
          />
        </div>
        
        <div class="form-group">
          <van-field
            v-model="loginForm.password"
            :type="showPassword ? 'text' : 'password'"
            name="password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
            left-icon="lock"
            class="custom-field"
          >
            <template #right-icon>
              <van-icon 
                :name="showPassword ? 'eye-o' : 'closed-eye'"
                @click="togglePasswordVisibility"
                class="password-toggle-icon"
              />
            </template>
          </van-field>
        </div>

        <div class="login-options">
          <van-checkbox v-model="rememberMe" class="remember-checkbox">
            记住密码
          </van-checkbox>
        </div>

        <div class="login-button">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="登录中..."
            class="submit-btn"
          >
            登录
          </van-button>
        </div>
        
        <!-- 网络测试按钮 -->
        <!-- <div class="network-test-section">
          <van-button
            type="warning"
            size="large"
            @click="goToNetworkTest"
            class="network-test-btn"
            block
            round
          >
            🔧 网络连接测试
          </van-button>
        </div> -->
      </van-form>

      <!-- 手机号登录表单 -->
      <van-form @submit="onPhoneSubmit" class="login-form" v-if="activeTab === 'phone'">
        <div class="form-group">
          <van-field
            v-model="phoneForm.phone"
            name="phone"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
            left-icon="phone-o"
            class="custom-field"
          />
        </div>
        
        <div class="form-group">
          <van-field
            v-model="phoneForm.code"
            name="code"
            placeholder="请输入短信验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
            left-icon="shield-o"
            class="custom-field"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                plain
                :disabled="codeCountdown > 0"
                @click="sendCode"
                class="code-btn"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}
              </van-button>
            </template>
          </van-field>
        </div>

        <div class="login-button">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="登录中..."
            class="submit-btn"
          >
            登录
          </van-button>
        </div>
        
        <!-- 网络测试按钮 -->
        <!-- <div class="network-test-section">
          <van-button
            type="warning"
            size="large"
            @click="goToNetworkTest"
            class="network-test-btn"
            block
            round
          >
            🔧 网络连接测试
          </van-button>
        </div> -->
      </van-form>
    </div>

    <!-- 底部装饰 -->
    <div class="bottom-decoration">
      <div class="mobile-illustration">
        <div class="phone-outline"></div>
        <div class="data-blocks">
          <div class="block block-1"></div>
          <div class="block block-2"></div>
          <div class="block block-3"></div>
        </div>
        <div class="chart-icon"></div>
        <div class="calendar-icon"></div>
      </div>
    </div>
  </div>
  
  <!-- 组织选择器 -->
  <OrgSelector
    v-model="showOrgSelector"
    :org-list="orgListData"
    @confirm="onOrgConfirm"
  />
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showFailToast, showSuccessToast } from 'vant'
import { useAuthStore } from '@/stores/auth'
import { loginAPI } from '@/api/auth'
import { EncryptLogin } from '@/utils/cryptoLogin'
import OrgSelector from '@/components/OrgSelector.vue'

const router = useRouter()
const authStore = useAuthStore()

// 跳转到网络测试页面
// const goToNetworkTest = () => {
//   console.log('🔧 点击网络测试按钮，准备跳转到网络测试页面...')
//   
//   // 先显示一个提示
//   showToast({
//     message: '正在跳转到网络测试页面...',
//     type: 'loading',
//     duration: 1000
//   })
//   
//   // 延迟跳转，确保用户看到提示
//   setTimeout(() => {
//     try {
//       // 尝试使用router.push
//       router.push('/network-test')
//       console.log('✅ 路由跳转成功')
//     } catch (error) {
//       console.error('❌ 路由跳转失败，尝试使用window.location:', error)
//       // 如果router.push失败，使用window.location
//       try {
//         window.location.href = '/network-test'
//         console.log('✅ window.location跳转成功')
//       } catch (locationError) {
//         console.error('❌ window.location跳转也失败:', locationError)
//         showToast({
//           message: '跳转失败: ' + locationError.message,
//           type: 'fail'
//         })
//       }
//     }
//   }, 500)
// }

const loading = ref(false)
const rememberMe = ref(false)
const activeTab = ref('username')
const codeCountdown = ref(0)
const showPassword = ref(false)

// 组织选择器相关
const showOrgSelector = ref(false)
const orgListData = ref([])

// 用户名登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 手机号登录表单
const phoneForm = reactive({
  phone: '',
  code: ''
})

// 标签页切换
const onTabChange = (name) => {
  activeTab.value = name
}

// 切换密码显示/隐藏
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 用户名登录提交
const onSubmit = async (values) => {
  loading.value = true
  
  try {
    // 对密码进行加密
    const encryptedPassword = EncryptLogin(values.password)
    
    // 调用后台登录接口
    const response = await loginAPI.loginWithPassword(
      values.username,
      encryptedPassword,
      1
    )
    
    // 检查响应状态
    if (response.code === 200 || response.success) {
      // 登录成功
      showSuccessToast('登录成功')
      
      // 获取组织列表
      const orgList = response.data?.orgList || []
      
      // 使用状态管理保存登录状态（先保存基本信息）
      authStore.login({
        token: response.data?.token || response.token || 'token-' + Date.now(),
        user: {
          username: response.data?.account?.username || values.username,
          name: response.data?.account?.accountName || response.data?.account?.username || '用户' + values.username,
          userId: response.data?.account?.id || response.data?.userId || response.data?.id,
          phone: response.data?.account?.phone,
          loginTime: new Date().toISOString(),
          orgList: orgList, // 保存组织列表
          ...response.data?.account
        }
      })
      
      // 处理组织选择
      if (orgList.length === 0) {
        // 没有组织信息，直接跳转
        router.push('/home')
      } else if (orgList.length === 1) {
        // 只有一个组织，直接设置
        const org = orgList[0]
        authStore.user.orgId = org.orgId
        authStore.user.orgName = org.orgName
        authStore.user.orgCode = org.orgCode
        localStorage.setItem('user', JSON.stringify(authStore.user))
        router.push('/home')
      } else {
        // 多个组织，显示选择器
        showOrgSelector.value = true
        orgListData.value = orgList
      }
    } else {
      // 登录失败
      showFailToast(response.message || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录错误:', error)
    
    // 处理不同类型的错误
    if (error.response?.status === 500) {
      showFailToast('后台服务错误，请联系管理员')
    } else if (error.response?.data?.message) {
      showFailToast(error.response.data.message)
    } else if (error.message) {
      showFailToast(error.message)
    } else if (error.code === 'NETWORK_ERROR' || error.message.includes('Network Error')) {
      showFailToast('网络连接失败，请检查网络或后台服务')
    } else {
      showFailToast('登录失败，请检查用户名和密码')
    }
  } finally {
    loading.value = false
  }
}

// 手机号登录提交
const onPhoneSubmit = async (values) => {
  loading.value = true
  
  try {
    // 调用后台登录接口
    const response = await loginAPI.loginWithPhone(
      values.phone,
      values.code,
      4
    )
    
    // 检查响应状态
    if (response.code === 200 || response.success) {
      // 登录成功
      showSuccessToast('登录成功')
      
      // 获取组织列表
      const orgList = response.data?.orgList || []
      
      // 使用状态管理保存登录状态（先保存基本信息）
      authStore.login({
        token: response.data?.token || response.token || 'token-' + Date.now(),
        user: {
          username: response.data?.account?.username || values.phone,
          name: response.data?.account?.accountName || response.data?.account?.username || '用户' + values.phone.slice(-4),
          userId: response.data?.account?.id || response.data?.userId || response.data?.id,
          phone: response.data?.account?.phone || values.phone,
          loginTime: new Date().toISOString(),
          orgList: orgList, // 保存组织列表
          ...response.data?.account
        }
      })
      
      // 处理组织选择
      if (orgList.length === 0) {
        // 没有组织信息，直接跳转
        router.push('/home')
      } else if (orgList.length === 1) {
        // 只有一个组织，直接设置
        const org = orgList[0]
        authStore.user.orgId = org.orgId
        authStore.user.orgName = org.orgName
        authStore.user.orgCode = org.orgCode
        localStorage.setItem('user', JSON.stringify(authStore.user))
        router.push('/home')
      } else {
        // 多个组织，显示选择器
        showOrgSelector.value = true
        orgListData.value = orgList
      }
    } else {
      // 登录失败
      showFailToast(response.message || '登录失败，请检查手机号和验证码')
    }
  } catch (error) {
    console.error('登录错误:', error)
    
    // 处理不同类型的错误
    if (error.response?.data?.message) {
      showFailToast(error.response.data.message)
    } else if (error.message) {
      showFailToast(error.message)
    } else {
      showFailToast('登录失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 发送验证码
const sendCode = async () => {
  if (!phoneForm.phone) {
    showFailToast('请先输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(phoneForm.phone)) {
    showFailToast('请输入正确的手机号')
    return
  }
  
  try {
    // 调用后台发送验证码接口
    const response = await loginAPI.sendSmsCode(phoneForm.phone)
    
    // 检查响应状态
    if (response.code === 200 || response.success) {
      showSuccessToast('验证码已发送')
      
      // 开始倒计时
      codeCountdown.value = 60
      const timer = setInterval(() => {
        codeCountdown.value--
        if (codeCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      showFailToast(response.message || '发送失败，请重试')
    }
  } catch (error) {
    console.error('发送验证码错误:', error)
    
    // 处理不同类型的错误
    if (error.response?.data?.message) {
      showFailToast(error.response.data.message)
    } else if (error.message) {
      showFailToast(error.message)
    } else {
      showFailToast('发送失败，请重试')
    }
  }
}

// 组织选择确认
const onOrgConfirm = async (selectedOrg) => {
  try {
    // 调用后台接口更新用户组织，后台会触发重新登录并返回新的token
    const response = await loginAPI.updateUserOrg(selectedOrg.orgId)
    
    // 更新用户信息和token
    if (authStore.user && response) {
      // 获取新的token（可能在response.token或response.data.token中）
      const newToken = response.token || response.data?.token
      
      // 更新用户信息
      const updatedUser = {
        ...authStore.user,
        ...response.data,  // 合并完整的用户信息
        orgId: selectedOrg.orgId,
        orgName: selectedOrg.orgName,
        orgCode: selectedOrg.orgCode,
        orgList: response.data?.orgList || authStore.user.orgList || []
      }
      
      // 更新 Pinia store
      authStore.user = updatedUser
      localStorage.setItem('user', JSON.stringify(updatedUser))
      
      // 更新token
      if (newToken) {
        authStore.token = newToken
        localStorage.setItem('token', newToken)
        console.log('Token已更新:', newToken)
      } else {
        console.warn('未找到新token')
      }
    }
    
    showSuccessToast(`已切换到：${selectedOrg.orgName}`)

    // 调用queryUserInfo接口获取最新的用户信息
    const userInfoResponse = await loginAPI.queryUserInfo();
    localStorage.setItem('user', JSON.stringify(userInfoResponse.data));
    
    // 使用 replace 而不是 push，避免历史记录问题
    router.replace('/home')
  } catch (error) {
    console.error('更新组织失败:', error)
    
    // 如果是token失效，响应拦截器已经处理了跳转，这里不需要额外处理
    if (error.message && error.message.includes('token失效')) {
      return
    }
    
    // 其他错误，仍然更新本地状态
    if (authStore.user) {
      const updatedUser = {
        ...authStore.user,
        orgId: selectedOrg.orgId,
        orgName: selectedOrg.orgName,
        orgCode: selectedOrg.orgCode
      }
      
      authStore.user = updatedUser
      localStorage.setItem('user', JSON.stringify(updatedUser))
    }
    
    showSuccessToast(`已切换到：${selectedOrg.orgName}`)
    router.replace('/home')
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #4A90E2 0%, #357ABD 50%, #2E5B8A 100%);
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

// 背景装饰
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  
  .bg-shapes {
    position: relative;
    width: 100%;
    height: 100%;
    
    .shape {
      position: absolute;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 8px;
      
      &.shape-1 {
        width: 60px;
        height: 60px;
        top: 20%;
        left: 10%;
        transform: rotate(45deg);
      }
      
      &.shape-2 {
        width: 40px;
        height: 40px;
        top: 60%;
        right: 15%;
        transform: rotate(-45deg);
      }
      
      &.shape-3 {
        width: 80px;
        height: 80px;
        top: 30%;
        right: 20%;
        border-radius: 50%;
        opacity: 0.3;
      }
      
      &.shape-4 {
        width: 30px;
        height: 30px;
        bottom: 30%;
        left: 20%;
        transform: rotate(30deg);
      }
    }
  }
}

// 顶部Logo区域
.login-header {
  position: relative;
  z-index: 2;
  padding: 60px 20px 40px;
  text-align: center;
  
  .logo-section {
    margin-bottom: 16px;
    
    .logo {
      margin-bottom: 16px;
      
      .logo-img {
        max-width: 120px;
        height: auto;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease;
        
        &:hover {
          transform: scale(1.05);
        }
      }
    }
    
    .app-title {
      color: white;
      font-size: 24px;
      font-weight: 600;
      margin: 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      line-height: 1.2;
    }
  }
}

// 登录表单容器
.login-container {
  position: relative;
  z-index: 2;
  flex: 1;
  background: white;
  border-radius: 24px 24px 0 0;
  padding: 32px 24px 40px;
  margin-top: auto;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
}

// 登录标签页
.login-tabs {
  margin-bottom: 32px;
  
  :deep(.van-tabs__wrap) {
    background: #F5F7FA;
    border-radius: 12px;
    padding: 4px;
  }
  
  :deep(.van-tab) {
    flex: 1;
    font-size: 16px;
    font-weight: 500;
  }
  
  :deep(.van-tab--active) {
    color: #07C160;
  }
  
  :deep(.van-tabs__line) {
    background: #07C160;
    height: 3px;
    border-radius: 2px;
  }
}

// 表单样式
.login-form {
  .form-group {
    margin-bottom: 20px;
    
    .custom-field {
      background: #F5F7FA;
      border-radius: 12px;
      margin-bottom: 16px;
      min-height: 56px;
      position: relative;
      padding: 16px;
      padding-left: 48px;
      
      :deep(.van-field__body) {
        padding: 0 !important;
        display: flex !important;
        align-items: center !important;
        min-height: 24px !important;
        position: relative !important;
      }
      
      :deep(.van-field__left-icon) {
        position: absolute !important;
        left: 16px !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        color: #999 !important;
        margin: 0 !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        width: 20px !important;
        height: 20px !important;
        z-index: 1 !important;
      }
      
      :deep(.van-field__control) {
        font-size: 16px;
        color: #333;
        background: transparent;
        line-height: 1.5;
        width: 100%;
        padding: 0;
      }
      
      :deep(.van-field__left-icon .van-icon) {
        font-size: 18px !important;
        line-height: 1 !important;
        display: block !important;
        margin: 0 !important;
      }
      
      :deep(.van-field__right-icon) {
        position: absolute !important;
        right: 16px !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        color: #999 !important;
        margin: 0 !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        width: 20px !important;
        height: 20px !important;
        z-index: 1 !important;
        cursor: pointer !important;
        transition: color 0.3s ease !important;
        
        &:hover {
          color: #1989fa !important;
        }
      }
      
      :deep(.van-field__right-icon .van-icon) {
        font-size: 18px !important;
        line-height: 1 !important;
        display: block !important;
        margin: 0 !important;
      }
      
      :deep(.van-field__button) {
        .code-btn {
          background: #07C160;
          border-color: #07C160;
          color: white;
          border-radius: 8px;
          font-size: 14px;
          padding: 8px 16px;
          
          &:disabled {
            background: #E5E5E5;
            border-color: #E5E5E5;
            color: #999;
          }
        }
      }
    }
  }
  
  .login-options {
    margin: 24px 0;
    
    .remember-checkbox {
      :deep(.van-checkbox__label) {
        color: #666;
        font-size: 14px;
      }
      
      :deep(.van-checkbox__icon--checked) {
        background: #07C160;
        border-color: #07C160;
      }
    }
  }
  
  .login-button {
    margin-top: 32px;
    
    .submit-btn {
      background: #07C160 !important;
      border-color: #07C160 !important;
      height: 50px;
      font-size: 16px;
      font-weight: 600;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
      width: 100%;
      
      &:active {
        background: #06AD56 !important;
        border-color: #06AD56 !important;
      }
    }
  }
}

// 底部装饰
.bottom-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 200px;
  z-index: 1;
  overflow: hidden;
  
  .mobile-illustration {
    position: relative;
    width: 100%;
    height: 100%;
    
    .phone-outline {
      position: absolute;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      width: 120px;
      height: 200px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      border-radius: 20px;
      background: rgba(255, 255, 255, 0.1);
    }
    
    .data-blocks {
      position: absolute;
      bottom: 60px;
      left: 20%;
      
      .block {
        position: absolute;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 4px;
        
        &.block-1 {
          width: 20px;
          height: 20px;
          bottom: 0;
          left: 0;
        }
        
        &.block-2 {
          width: 16px;
          height: 16px;
          bottom: 25px;
          left: 10px;
        }
        
        &.block-3 {
          width: 12px;
          height: 12px;
          bottom: 45px;
          left: 20px;
        }
      }
    }
    
    .chart-icon {
      position: absolute;
      bottom: 80px;
      right: 30%;
      width: 24px;
      height: 24px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 4px;
      
      &::before {
        content: '';
        position: absolute;
        top: 4px;
        left: 4px;
        right: 4px;
        bottom: 4px;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 2px;
      }
    }
    
    .calendar-icon {
      position: absolute;
      bottom: 120px;
      right: 20%;
      width: 20px;
      height: 20px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 4px;
      
      &::before {
        content: '';
        position: absolute;
        top: 2px;
        left: 2px;
        right: 2px;
        height: 2px;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 1px;
      }
    }
  }
}

// 平板适配
@media screen and (min-width: 768px) {
  .login-container {
    max-width: 500px;
    margin: 0 auto;
    border-radius: 24px;
    margin-top: 40px;
  }
  
  // 网络测试按钮样式
  // .network-test-section {
  //   margin: 20px 0 10px 0;
  //   
  //   .network-test-btn {
  //     background: #ff9500 !important;
  //     border: none !important;
  //     color: white !important;
  //     font-size: 14px !important;
  //     font-weight: bold !important;
  //     height: 44px !important;
  //     border-radius: 22px !important;
  //     box-shadow: 0 2px 8px rgba(255, 149, 0, 0.3) !important;
  //   }
  // }
  
  .login-header {
    padding: 80px 20px 60px;
    
    .logo-section .app-title {
      font-size: 28px;
    }
  }
  
  .bottom-decoration {
    height: 300px;
    
    .mobile-illustration {
      .phone-outline {
        width: 150px;
        height: 250px;
      }
    }
  }
}
</style>
